<template>
  <el-dialog
    title="新建设备类型参数"
    :visible.sync="dialogVisible"
    width="600px"
  >
    <el-form
      ref="addSearchForm"
      :model="searchForm"
      :label-width="formLabelWidth"
      :show-message="false"
    >
      <el-form-item
        prop="name"
        label="名称"
        required
      >
        <el-input
          class="input"
          v-model="searchForm.name"
          auto-complete="off"
          placeholder="请输入设备参数名称"
        ></el-input>
      </el-form-item>
      <el-form-item
        prop="displayName"
        label="显示名称"
        required
      >
        <el-input
          class="input"
          v-model="searchForm.displayName"
          auto-complete="off"
          placeholder="请输入设备参数显示名称"
        ></el-input>
      </el-form-item>
      <el-form-item
        prop="unit"
        label="单位"
      >
        <el-input
          class="input"
          v-model="searchForm.unit"
          auto-complete="off"
          placeholder="请输入设备参数单位"
        ></el-input>
      </el-form-item>
      <el-form-item
        prop="description"
        label="描述"
      >
        <el-input
          @keyup.enter.native="add"
          class="input"
          v-model="searchForm.description"
          auto-complete="off"
          placeholder="请输入设备参数描述"
        ></el-input>
      </el-form-item>
    </el-form>
    <span
      slot="footer"
      class="dialog-footer"
    >
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button
        type="primary"
        @click="add"
        :loading="btnLoading"
      >确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { validateForm } from './service';
import { Message } from 'element-ui';
import { parseError } from '../../../utils/index';
import { createDeviceParameterApi } from '../../../api/deviceParameter';

export default {
  data() {
    this.formLabelWidth = '120px';
    return {
      dialogVisible: false,
      btnLoading: false,
      searchForm: {
        name: '',
        displayName: '',
        unit: '',
        description: ''
      }
    };
  },
  watch: {
    dialogVisible: {
      handler(value) {
        if (!value) this.$refs.addSearchForm.resetFields();
      }
    }
  },
  methods: {
    showDialog() {
      this.dialogVisible = true;
    },
    add() {
      const validError = validateForm(this.searchForm);
      if (validError) return Message.warning(validError);
      this.btnLoading = true;
      createDeviceParameterApi(
        this.searchForm.name,
        this.searchForm.displayName,
        this.searchForm.unit,
        this.searchForm.description
      )
        .then(res => {
          Message.success('添加成功');
          this.dialogVisible = false;
          this.$emit('refresh');
        })
        .catch(error => Message.error(parseError(error)))
        .finally(() => (this.btnLoading = false));
    }
  }
};
</script>

<style lang="scss" scoped>
.input {
  width: 300px;
}
</style>
